package com.hermit.qmst;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.UI.main.ContactsFragment;
import com.hermit.qmst.UI.main.DialNewFragment;
import com.hermit.qmst.UI.main.FragmentTabHost;
import com.hermit.qmst.csipsimple.api.ISipService;
import com.hermit.qmst.csipsimple.api.SipManager;
import com.hermit.qmst.csipsimple.api.SipProfile;
import com.hermit.qmst.csipsimple.api.SipUri;
import com.hermit.qmst.csipsimple.db.DBProvider;
import com.hermit.qmst.csipsimple.models.Filter;
import com.hermit.qmst.csipsimple.service.SipService;
import com.hermit.qmst.csipsimple.utils.PreferencesProviderWrapper;
import com.hermit.qmst.csipsimple.utils.PreferencesWrapper;
import com.hermit.qmst.csipsimple.wizards.WizardIface;
import com.hermit.qmst.csipsimple.wizards.WizardUtils;
import com.hermit.qmst.request.DownLoadAPK;
import com.hermit.qmst.request.RequestTask;
import com.hermit.qmst.request.RequestTaskInterface;
import com.hermit.qmst.request.UpdateProcessInterface;
import com.hermit.qmst.service.GetImageService;
import com.hermit.qmst.service.SysMessageIntentService;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.FileUtils;
import com.hermit.qmst.tools.Log;
import com.hermit.qmst.tools.ParseXML;
import com.hermit.qmst.tools.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends FragmentActivity implements View.OnClickListener, UpdateProcessInterface, RequestTaskInterface {
    private static final String TAG = "FragmentActivity";
    private FragmentTabHost mTabHost;
    private AlertDialog mProgressDialog;
    private ProgressBar mProgressBar;
    private int requestType = 0;
    private String mAPKUrlPath = "";
    public ISipService mISipService;//启动直拨服务
    private SipProfile mAccount = null;
    private WizardIface mWizardIface;
    private PreferencesProviderWrapper mPreferencesProviderWrapper;
    private PreferencesWrapper mPreferencesWrapper;

    private static MainActivity mInstance;
    public LinearLayout mTabbar;

    //定义底部栏按钮
    TextView mtvTab1;
    TextView mtvTab2;
    TextView mtvTab3;
    TextView mtvTab4;
    TextView mtvTab5;
    private String appVersion;
//    //创建数据存放Fragment
//    private Class mFragmentArray[] = {DialNewFragment.class};
//
//    //下面两个数组并没有真正显示出来
//    private int mImageViewArray[] = {R.drawable.tabbar_1};
//    private String mTextViewArray[] = {"电话本"};

    private Class mFragmentArray[] = {DialNewFragment.class, ContactsFragment.class};
    //下面两个数组并没有真正显示出来
    private int mImageViewArray[] = {R.drawable.tabbar_1, R.drawable.tabbar_2};
    private String mTextViewArray[] = {"电话本", "联系人"};

    public static MainActivity getInstant() {
        return mInstance;
    }

    private ImageView iv_back;
    private TextView tv_title, iv_right;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_main);
        mInstance = this;
        mPreferencesProviderWrapper = new PreferencesProviderWrapper(this);
        mPreferencesWrapper = new PreferencesWrapper(this);
        setMyDefaultParams(mPreferencesWrapper);

        initView();
        Preferences preferences = new Preferences(this);
        Common.myPhone = preferences.getPreferenceStringValue(Preferences.MY_PHONE);
        Common.myPassword = preferences.getPreferenceStringValue(Preferences.MY_PASSWORD);
        Common.mIsAutoAnswer = preferences.getPreferenceBooleanValue(Preferences.AUTO_RING);
        Common.mSipAccout = preferences.getPreferenceStringValue(preferences.SIP_ACCOUNT);
        //代理商
        Common.mAgentId = preferences.getPreferenceStringValue(Preferences.SIP_AGENT);
        Common.mAgentThirdId = preferences.getPreferenceStringValue(Preferences.SIP_AGENT_THIRD);
        Common.mUserId = preferences.getPreferenceStringValue(Preferences.USER_ID);

        checkUpdateAPK();

        Intent intent = new Intent(this, GetImageService.class);
        startService(intent);

        startPendingIntent(this);

        if (Common.mSipAccout == null || Common.mSipAccout.length() == 0) {
            request_login();
        } else {
            getSipAccountId();
        }
        String appName = this.getString(R.string.app_name);
        Log.i("appName", appName, true);
    }

    public int getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return Integer.valueOf(version.replace(".", ""));
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //连接服务
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mISipService = ISipService.Stub.asInterface(service);


        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mISipService = null;
            Log.i(TAG, "onServiceDisconnected is null", true);
        }
    };

    //获取此类的实例

    public static final MainActivity getInstance() {

        if (mInstance != null) {
            return mInstance;
        } else {
            return null;
        }
    }

    private void initView() {
        //初始化tabhost
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.getTabWidget().setDividerDrawable(android.R.color.transparent);
        int count = mFragmentArray.length;

        for (int i = 0; i < count; i++) {

            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextViewArray[i])
                    .setIndicator(mTextViewArray[i], getResources().getDrawable(mImageViewArray[i]));
            mTabHost.addTab(tabSpec, mFragmentArray[i], null);

        }

        mTabbar = (LinearLayout) findViewById(R.id.tabbar);

        //监听底部栏按钮
        mtvTab1 = (TextView) findViewById(R.id.tv_tab_1);
        mtvTab1.setOnClickListener(this);
        mtvTab1.setSelected(true);
        mtvTab2 = (TextView) findViewById(R.id.tv_tab_2);
        mtvTab2.setOnClickListener(this);
        mtvTab3 = (TextView) findViewById(R.id.tv_tab_3);
        mtvTab3.setOnClickListener(this);
        mtvTab4 = (TextView) findViewById(R.id.tv_tab_4);
        mtvTab4.setOnClickListener(this);
        mtvTab5 = (TextView) findViewById(R.id.tv_tab_5);
        mtvTab5.setOnClickListener(this);

        //设置当前fragment
        mTabHost.setCurrentTab(0);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        tv_title = (TextView) findViewById(R.id.tv_title);
        iv_right = (TextView) findViewById(R.id.iv_right);
        iv_right.setVisibility(View.VISIBLE);
        iv_right.setOnClickListener(this);

        tv_title.setText("通话记录");
        isFister = true;
        iv_right.setText("联系人");


    }

    private boolean isFister = true;

    //清除底部栏按钮状态
    private void clearIndicatorState() {
        mtvTab1.setSelected(false);
        mtvTab2.setSelected(false);
        mtvTab3.setSelected(false);
        mtvTab4.setSelected(false);
        mtvTab5.setSelected(false);
    }

    //设置当前fragment
    public void setCurrentFragment(int index) {
        if (mTabHost.getCurrentTab() != index) {
            mTabHost.setCurrentTab(index);
            clearIndicatorState();
            switch (index) {
                case 0:
                    mtvTab1.setSelected(true);
                    break;
                case 1:
                    mtvTab2.setSelected(true);
                    break;
                case 2:
                    mtvTab3.setSelected(true);
                    break;
                case 3:
                    mtvTab4.setSelected(true);
                    break;
                case 4:
                    mtvTab5.setSelected(true);
                    break;
                default:
                    break;

            }
        } else if (mTabHost.getCurrentTab() == 0 && index == 0) {
            //CallLogFragment.getInstance().showOrHideDial();
        }
    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_right:
                isFister = false;
                tv_title.setText("联系人");
                setCurrentFragment(1);
                iv_right.setVisibility(View.INVISIBLE);
                mTabbar.setVisibility(View.GONE);
                break;
            case R.id.iv_back:
                if (isFister) {
                    finish();
                    mTabbar.setVisibility(View.GONE);
                } else {
                    tv_title.setText("电话本");
                    isFister = true;
                    setCurrentFragment(0);
                    mTabbar.setVisibility(View.VISIBLE);
                }
                iv_right.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        //清除图片
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileUtils fileUtils = new FileUtils();
                fileUtils.deleteFileByDate(Common.getDialImageDirPath());
            }
        }).start();

        // request_sign();
        startSipService();
        Intent intent1 = new Intent(this, SipService.class);
        //intent1.setAction(SipManager.INTENT_SIP_SERVICE);
        //绑定SIP服务
        boolean b = this.getApplicationContext().bindService(intent1, mConnection, Context.BIND_AUTO_CREATE);

        if (!b) {
            Log.i(TAG, "bindService is failed", true);
        }
        setMyDefaultParams(mPreferencesWrapper);

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mConnection != null) {
            this.getApplicationContext().unbindService(mConnection);

        }
        stopSipService();
    }

    private static AlarmManager am;
    private static PendingIntent pendingIntent;

    /**
     * 使用 AlarmManager 来 定时启动服务
     */
    public static void startPendingIntent(Context context) {
        am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, SysMessageIntentService.class);// 启动示例Service

        pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        long interval = DateUtils.MINUTE_IN_MILLIS * 30 + (long) Math.random() * 1000 * 100;// 30分钟一次

        long firstWake = System.currentTimeMillis() + 5000;

        am.setRepeating(AlarmManager.RTC, firstWake, interval,
                pendingIntent);

    }


    private void checkUpdateAPK() {
        requestType = 1;
//        String url = Common.submitUpdatePath() + "0&agent_name="+this.getString(R.string.app_name_py);
        String url = Common.submitUpdatePath() + getVersion() + "&agent_name=" + this.getString(R.string.app_name_py);
        Log.i(TAG + "_url", url, true);
        RequestTask _RequestTask = new RequestTask(this, url, "", "POST", this);
        _RequestTask.execute();
    }


    private void showUpdateVersionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("软件更新")
                .setMessage("检查到新的版本,是否更新")
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showUpdateDialog();
                        downloadAPK();

                    }
                }).setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }

    private void downloadAPK() {
        requestType = 2;
        if (mAPKUrlPath.length() > 0) {
            DownLoadAPK downLoadAPK = new DownLoadAPK(this, mAPKUrlPath, this, this);
            downLoadAPK.execute();
        }

    }

    private void showUpdateDialog() {
        View v = LayoutInflater.from(this).inflate(R.layout.update_probar, null);
        mProgressBar = (ProgressBar) v.findViewById(R.id.progressBar1);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("正在更新...                              ")

                .setView(v);

        mProgressDialog = builder.create();
        mProgressDialog.show();

    }

    @Override
    public void postExecute(String paramString) {
        if (paramString != null && paramString.length() > 0) {
            Log.i(TAG, "更新：" + paramString, true);
            try {
                JSONObject object = new JSONObject(paramString);
                mAPKUrlPath = object.getString("url");
                showUpdateVersionDialog();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (requestType == 2) {

                if (mProgressDialog != null) {
                    mProgressDialog.dismiss();
                }
                String fileName = Environment.getExternalStorageDirectory() + "/" + Common.mApkName;
                if (paramString.equals(fileName)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.parse("file://" + fileName), "application/vnd.android.package-archive");
                    startActivity(intent);
                } else {
                    String[] command = {"chmod", "777", paramString};
                    ProcessBuilder builder = new ProcessBuilder(command);
                    try {
                        builder.start();
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setDataAndType(Uri.parse("file://" + fileName), "application/vnd.android.package-archive");
                        startActivity(intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    @Override
    public void processUpate(int value) {
        mProgressBar.setProgress(value);

    }


   /* @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }*/

    //启动SIP服务
    private void startSipService() {
        Thread t = new Thread("StartSip") {

            public void run() {
                Intent intent = new Intent(MainActivity.this, SipService.class);
                intent.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, new ComponentName(MainActivity.this, MainActivity.class));
                startService(intent);
                //postStartSipService();
            }
        };
        t.start();
    }


    //启动SIP服务
    private void stopSipService() {
        Thread t = new Thread("StartSip") {

            public void run() {
                Intent intent = new Intent(MainActivity.this, SipService.class);
                intent.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, new ComponentName(MainActivity.this, MainActivity.class));
                stopService(intent);
                // postStartSipService();
            }

            ;

        };
        t.start();
    }

    private void request_login() {

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = Common.submitLoginPath() + "regnum=" + Common.myPhone + "&regpwd=" + Common.myPassword;

        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                Log.i("LoginActivity", s, true);
                if (s != null && s.length() > 0) {

                    String code = ParseXML.parseResponseXML(s, "Ret");

                    if (code.equals("0")) {
                        Preferences p = new Preferences(MainActivity.this);
                        //直拨账号
                        String acctName = ParseXML.parseResponseXML(s, "AcctName");
                        p.setPreferenceStringValue(Preferences.SIP_ACCOUNT, acctName);
                        Common.mSipAccout = acctName;
                        saveAccount("BASIC", Common.mSipAccout, Common.myPassword, Common.mIP, Common.mSipPort);

                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });


        requestQueue.add(request);
    }

    private void getSipAccountId() {
        ArrayList<SipProfile> accounts = new ArrayList<SipProfile>();
        accounts = SipProfile.getAllProfiles(this, true, new String[]{
                SipProfile.FIELD_ID,
                SipProfile.FIELD_ACC_ID,
                SipProfile.FIELD_DISPLAY_NAME,
                SipProfile.FIELD_WIZARD,
                SipProfile.FIELD_USERNAME,

        });

        Log.i(TAG, "账号个数 = " + accounts.size(), true);

        if (accounts.size() > 0) {
            for (int i = 0; i < accounts.size(); i++) {
                SipProfile account = accounts.get(i);
                if (account.username.equals(Common.mSipAccout)) {
                    Common.mSipAccountId = account.id;
                }
            }
        }

        if (accounts.size() == 0 || Common.mSipAccountId == -1) {
            saveAccount("BASIC", Common.mSipAccout, Common.myPassword, Common.mIP, Common.mSipPort);
            Log.i(TAG, "saveAccount =  BASIC", true);
        }
    }

    private void saveAccount(String wizardId, String pSipAccount, String pSipPwd, String pSipIp, String pSipPort) {

        ArrayList<SipProfile> accounts = new ArrayList<SipProfile>();
        if (accounts != null && accounts.size() > 0) {
            accounts = SipProfile.getAllProfiles(this, false, new String[]{
                    SipProfile.FIELD_ID,
                    SipProfile.FIELD_ACC_ID,
                    SipProfile.FIELD_ACTIVE,
                    SipProfile.FIELD_DISPLAY_NAME,
                    SipProfile.FIELD_WIZARD,
                    SipProfile.FIELD_USERNAME

            });
            try {
                mISipService.removeAllAccounts();
                getContentResolver().delete(SipProfile.ACCOUNT_URI, null, null);
                /*for (int i = 0; i < accounts.size(); i++) {
                    getContentResolver().delete(SipProfile.ACCOUNT_URI,  SipProfile.FIELD_USERNAME + "=" + accounts.get(i).username, null);
				}*/
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }


        mAccount = SipProfile.getProfileFromDbId(this, -1, DBProvider.ACCOUNT_FULL_PROJECTION);
        boolean needRestart = false;

        WizardUtils.WizardInfo wizardInfo = WizardUtils.getWizardClass(wizardId);

        try {
            mWizardIface = (WizardIface) wizardInfo.classObject.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        PreferencesWrapper prefs = new PreferencesWrapper(this);
        mAccount = buildAccount(mAccount, pSipAccount, pSipPwd, pSipIp, pSipPort);
        mAccount.wizard = wizardId;

        if (mAccount.id == SipProfile.INVALID_ID) {
            // This account does not exists yet
            prefs.startEditing();
            mWizardIface.setDefaultParams(prefs);
            prefs.endEditing();
            Uri uri = getContentResolver().insert(SipProfile.ACCOUNT_URI, mAccount.getDbContentValues());
            mAccount.id = ContentUris.parseId(uri);
            List<Filter> filters = mWizardIface.getDefaultFilters(mAccount);
            if (filters != null) {
                for (Filter filter : filters) {
                    // Ensure the correct id if not done by the wizard
                    filter.account = (int) mAccount.id;
                    getContentResolver().insert(SipManager.FILTER_URI, filter.getDbContentValues());

                }
            }
            needRestart = mWizardIface.needRestart();


        } else {
            prefs.startEditing();
            mWizardIface.setDefaultParams(prefs);
            prefs.endEditing();
            getContentResolver().update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, mAccount.id), mAccount.getDbContentValues(), null, null);
        }

        Common.mSipAccountId = mAccount.id;

        if (needRestart) {
            Intent intent = new Intent(SipManager.ACTION_SIP_REQUEST_RESTART);
            sendBroadcast(intent);
        }

    }

    private SipProfile buildAccount(SipProfile account, String pSipAccount, String pSipPwd, String pSipIp, String pSipPort) {


        account.display_name = getString(R.string.app_name);
        String[] serverParts = (pSipIp + ":" + pSipPort).split(":");
        account.acc_id = "<sip:" + SipUri.encodeUser(pSipAccount) + "@" + serverParts[0].trim() + ">";
        String regUri = "sip:" + pSipIp + ":" + pSipPort;
        account.reg_uri = regUri;
        account.proxies = new String[]{regUri};
        account.realm = "*";
        account.username = pSipAccount;
        account.data = pSipPwd;
        account.scheme = SipProfile.CRED_SCHEME_DIGEST;
        account.datatype = SipProfile.CRED_DATA_PLAIN_PASSWD;
        account.transport = SipProfile.TRANSPORT_UDP;
        return account;
    }

    private void setMyDefaultParams(PreferencesWrapper preferencesWrapper) {

        //
        //preferencesWrapper.setCodecPriority("g729/8000/1", "nb", "245");
        preferencesWrapper.setCodecPriority("PCMA/8000/1", "nb", "208");
        preferencesWrapper.setCodecPriority("PCMU/8000/1", "nb", "207");
        preferencesWrapper.setCodecPriority("PCMA/8000/1", "wb", "245");
        preferencesWrapper.setCodecPriority("PCMU/8000/1", "wb", "244");
        //preferencesWrapper.setCodecPriority("g729/8000/1", "wb", "243");
        preferencesWrapper.setCodecPriority("g729/8000/1", "nb", "240");
        preferencesWrapper.setCodecPriority("g729/8000/1", "wb", "240");

        preferencesWrapper.setPreferenceBooleanValue("integrate_with_native_dialer", false);
        preferencesWrapper.setPreferenceBooleanValue("use_3g_in", true);
        preferencesWrapper.setPreferenceBooleanValue("use_3g_out", true);
        preferencesWrapper.setPreferenceBooleanValue("use_gprs_in", true);
        preferencesWrapper.setPreferenceBooleanValue("use_gprs_out", true);
        preferencesWrapper.setPreferenceBooleanValue("use_edge_in", true);
        preferencesWrapper.setPreferenceBooleanValue("use_edge_out", true);
        preferencesWrapper.setPreferenceBooleanValue("use_anyway_in", true);
        preferencesWrapper.setPreferenceBooleanValue("use_anyway_out", true);
        preferencesWrapper.setPreferenceBooleanValue("use_alternate_unlocker", false);
        preferencesWrapper.setPreferenceBooleanValue("support_multiple_calls", false);

        //Intent _Intent = new Intent(YaloeActivity.this, Codecs.class);
        // startActivity(_Intent);
    }

}
